package com.findfuture.demo.service.impl;

import com.findfuture.common.dao.HibernateDaoImpl;
import com.findfuture.common.util.FileUploadUtils;
import com.findfuture.common.util.QueryResult;
import com.findfuture.demo.model.Images;
import com.findfuture.demo.service.IImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Alex
 * Date: 11-12-19
 * Time: 下午8:57
 * To change this template use File | Settings | File Templates.
 */
@Service("imageService")
public class ImageServiceImpl implements IImageService {
    @Autowired
    private HibernateDaoImpl commonDao;

    @Override
    public void deleteImage(int id) throws Exception {
        commonDao.setEntryClass(Images.class);
        Images images = (Images) commonDao.fetch(id);
        String url = images.getUrl();
        String thumb = images.getThumb();
        commonDao.delete(images);
        FileUploadUtils.deleteWebAppFile(url);
        FileUploadUtils.deleteWebAppFile(thumb);
    }

    @Override
    public void addImage(Images image) throws Exception {
        commonDao.setEntryClass(Images.class);
        commonDao.save(image);
    }

    @Override
    public void updateDesc(int imageId, String desc) throws Exception {
        commonDao.setEntryClass(Images.class);
        commonDao.execute("update " + Images.class.getSimpleName() + " set descript = ? where id = ?", desc, imageId);
    }

    @Override
    public List<Images> getImages() throws Exception {
        commonDao.setEntryClass(Images.class);
        return commonDao.query();  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public QueryResult getImagesByWhere(String where, int pageNum, int pageSize) throws Exception {
        commonDao.setEntryClass(Images.class);
        QueryResult result = commonDao.query("from " + Images.class.getSimpleName() + " i where 1=1 " + where, pageNum, pageSize, null);
        return result;
    }

    @Override
    public Images getImageById(int id) {
        commonDao.setEntryClass(Images.class);
        return (Images) commonDao.fetch(id);
    }

    @Override
    public void updateImage(Images images) throws Exception {
        commonDao.setEntryClass(Images.class);
        commonDao.update(images);
    }
}
